<template>
  <el-card style="width: 500px; margin: 150px auto">
    <el-form
      label-width="100px"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
    >
      <el-form-item label="手机号码" prop="phone" required>
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" required>
        <el-input v-model="ruleForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">立即登录</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { gfRequest } from "../../utils/gfRequest";

export default {
  name: "Login",
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.repassword !== "") {
          this.$refs.ruleForm.validateField("repassword");
        }
        callback();
      }
    };
    return {
      ruleForm: {
        phone: "",
        password: "",
      },
      rules: {
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { min: 11, max: 11, message: "手机号码格式错误", trigger: "blur" },
        ],
        password: [
          { validator: validatePassword, trigger: "blur" },
          { min: 6, max: 12, message: "密码应为6到12位", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    cancel() {
      this.$router.push("/");
    },
    async login() {
      const { phone, password } = this.ruleForm;
      const url = `/login/cellphone?phone=${phone}&password=${password}`;
      const response = await gfRequest(url);
      localStorage.setItem("nickname", response.data.profile.nickname);
      this.$router.replace("/");
    },
  },
};
</script>

<style>
</style>